<?php
#注册插件
RegisterPlugin("mzDanron", "ActivePlugin_mzDanron");

function ActivePlugin_mzDanron()
{
  // Add_Filter_Plugin('Filter_Plugin_Zbp_Load','InstallPlugin_mzDanron');
  Add_Filter_Plugin('Filter_Plugin_Admin_TopMenu', 'mzDanron_AddMenu');
  Add_Filter_Plugin('Filter_Plugin_ViewPost_Template', 'mzDanron_Main');
  Add_Filter_Plugin('Filter_Plugin_ViewSearch_Template', 'mzDanron_Main');
  Add_Filter_Plugin('Filter_Plugin_ViewList_Template', 'mzDanron_Main');
  Add_Filter_Plugin('Filter_Plugin_Zbp_BuildTemplate', 'mzDanron_Gentemplate');
  Add_Filter_Plugin('Filter_Plugin_ViewComment_Template', 'mzDanron_ViewCMT');
  Add_Filter_Plugin('Filter_Plugin_ViewList_Core', 'mzDanron_canonical');
}
function mzDanron_canonical()
{
  global $zbp;
  $fpargs = func_get_args();
  $url = $fpargs[7]->UrlRule;
  $zbp->fullcurrenturl = $url->Make();
}
function mzDanron_AddMenu(&$m)
{
  global $zbp;
  $m[] = MakeTopMenu("root", '<b>主题配置</b>', $zbp->host . "zb_users/theme/mzDanron/main.php", "", "mzDanron");
}
function mzDanron_ViewCMT(&$template)
{
  global $zbp;
  $type = $template->GetTags('type');
  // $comments = $template->GetTags('comments');
  $comment = $template->GetTags('comment');
  if ($comment->ParentID > 0) {
    $commentParent = $zbp->GetCommentByID($comment->ParentID);
    $template->SetTags('MizuPaN', array($comment->ParentID => $commentParent->Author->StaticName));
    $template->SetTemplate("comment-reply");
  }
}
function mzDanron_Main(&$template)
{

  global $zbp;
  if ($tag = $template->GetTags('articles')) {
    foreach ($tag as $article) {
      mzDanron_SetIMG($article);
    }
  } else if ($article = $template->GetTags('article')) {
    mzDanron_SetIMG($article);
  }
}
function mzDanron_SetIMG($post)
{
  global $bloghost;
  if (!isset($post->FistImg)) {
    //$randnum=rand(1, 19);
    $randnum = $post->ID % 19 + 1;
    $pattern = "/<img[^>]+src=\"(?<url>[^\"]+\.(gif|jpg|png))\"[^>]*>/";
    $content = $post->Content;
    $matchContent = array();
    preg_match($pattern, $content, $matchContent);
    if (isset($matchContent["url"])) {
      $temp = $matchContent["url"];
    } else {
      $temp = mzDanron_Path("v-noimg", "host") . $randnum . ".jpg";
    }
    $post->FistImg = $temp;
  }
}
function mzDanron_MiniImage($src, $width, $height, $check = false)
{
  global $zbp;
  $url = str_replace($zbp->host, '{$host}', $src);
  if (stripos($url, '{$host}') === false) {
    echo $url;
    return;
  }
  if ($check && stripos($url, "var/noimg/") !== false) {
    $url = str_replace('{$host}', $zbp->host, $url);
    echo $url;
    return;
  }
  $url = str_replace("/", '-', $url);
  $url = str_replace('{$host}', "{$zbp->host}zb_users/upload/mini/{$width}_{$height}/", $url);
  echo $url;
  return;
}
function mzDanron_Gentemplate(&$templates)
{
  global $zbp;
  $templates['n-slide'] = "";
  $templates['n-hot'] = "";
  $templates['n-rand'] = "";
  if (!$zbp->template->HasTemplate("m-slide")) {
    return;
  }
  // 读取幻灯片配置文件
  $uFile = mzDanron_Path("u-slide");
  if (!is_file($uFile)) {
    return;
  }
  // return;
  $obj = json_decode(file_get_contents($uFile));
  $zbp->template->SetTags('slides', $obj->slides);
  $zbp->template->SetTags('labels', $obj->labels);
  $templates['n-slide'] = $zbp->template->Output("m-slide");
  $templates['n-slide'] .= '{php}$footer .= \'<script src="' . $zbp->host . 'zb_users/theme/mzDanron/script/swiper-3.4.2.jquery.min.js"></script>\'{/php}';
  $templates['n-slide'] .= '{php}$footer .= \'<script src="' . $zbp->host . 'zb_users/theme/mzDanron/script/swiper-act.js"></script>\'{/php}';
  $templates['n-hot'] = mzDanron_GenHot($zbp->config("mzDanron")->focusNums);
  $templates['n-rand'] = mzDanron_GenRnd($zbp->config("mzDanron")->focusNums);
}
function mzDanron_GenHot($nums)
{
  global $zbp;
  $w = array();
  $w[] = array('=', 'log_Type', 0);
  $order = array('log_ViewNums' => 'DESC');
  $limit = $nums;

  $articles = $zbp->GetArticleList(
    array('*'),
    $w,
    $order,
    $limit,
    null
  );
  $rltHtml = "<ul>";
  foreach ($articles as $article) {
    $rltHtml .= "<li><a href=\"{$article->Url}\" title=\"{$article->Title}\">{$article->Title}</a></li>";
  }
  return $rltHtml . "</ul>";
}
function mzDanron_GenRnd($nums)
{
  global $zbp;
  $sql = $zbp->db->sql->Select(
    $zbp->table['Post'],
    array("MIN(log_ID)", "MAX(log_ID)"),
    array(
      array('=', 'log_Type', '0'),
      array('=', 'log_Status', '0'),
    ),
    array('log_PostTime' => 'ASC'),
    null,
    null
  );
  $array = $zbp->db->Query($sql);
  list($min, $max) = explode(':', join(":", $array[0]));
  // list($min, $max) = $array[0];
  // 判断相等时仍然有$min和$min+1两种取法
  if ($max - $nums >= $min) {
    $i = mt_rand($min, $max - $nums + 1);
  } else {
    $i = $min;
  }
  $order = '';
  $where = array(
    array('=', 'log_Status', '0'),
    array('>=', 'log_ID', $i)
  );
  $articles = $zbp->GetArticleList(array('*'), $where, $order, array($nums), '');
  $rltHtml = "<ul>";
  foreach ($articles as $article) {
    $rltHtml .= "<li><a href=\"{$article->Url}\" title=\"{$article->Title}\">{$article->Title}</a></li>";
  }
  return $rltHtml . "</ul>";
}
// function mzDanron_QR()
// {
//   global $zbp;
//   $result = $zbp->host . 'zb_users/theme/mzDanron/';
//   $qrImgs = array();
//   $qrImgs['wx'] = $result . 'usr/qr-wx.png';
//   $qrImgs['qq'] = $result . 'usr/qr-qq.png';
//   $qrImgs['ali'] = $result . 'usr/qr-ali.png';
//   return $qrImgs;
// }
function mzDanron_Path($file, $t = 'path')
{
  global $zbp;
  $result = $zbp->$t . 'zb_users/theme/mzDanron/';
  switch ($file) {
    case 'u-qr-wx':
      return $result . 'usr/qr-wx.png';
      break;
    case 'u-qr-qq':
      return $result . 'usr/qr-qq.png';
      break;
    case 'u-qr-ali':
      return $result . 'usr/qr-ali.png';
      break;
      // 轮播配置项
    case "u-slide":
      return $result . "usr/slide.json";
      break;
    case "v-slide":
      return $result . "var/slide.json";
      break;
    case "u-label":
      return $result . "usr/label/";
      break;
    case "v-label":
      return $result . "var/label/";
      break;
      // fav+logo
    case 'u-fav':
      return $result . 'usr/favicon.ico';
      break;
    case 'v-fav':
      return $result . 'var/favicon.ico';
      break;
    case 'u-logo':
      return $result . 'usr/logo.png';
      break;
    case 'v-logo':
      return $result . 'var/logo.png';
      break;
      // ---
    case 'v-noimg':
      return $result . 'var/noimg/';
      break;
      // ---
    case 'usr':
      return $result . 'usr/';
      break;
    case 'var':
      return $result . 'var/';
      break;
    case 'main':
      return $result . 'main.php';
      break;
    default:
      return $result . $file;
  }
}
function mzDanron_Time($ptime, $isStr = false)
{
  $ptime = $isStr ? strtotime($ptime) : $ptime;
  $etime = time() - $ptime;
  if ($etime < 1) return '刚刚';
  $interval = array(
    12 * 30 * 24 * 60 * 60  =>  '年前 (' . date('Y-m-d', $ptime) . ')',
    30 * 24 * 60 * 60       =>  '个月前 (' . date('m-d', $ptime) . ')',
    7 * 24 * 60 * 60        =>  '周前 (' . date('m-d', $ptime) . ')',
    24 * 60 * 60            =>  '天前',
    60 * 60                 =>  '小时前',
    60                      =>  '分钟前',
    1                       =>  '秒前'
  );
  foreach ($interval as $secs => $str) {
    $d = $etime / $secs;
    if ($d >= 1) {
      $r = round($d);
      return $r . $str;
    }
  };
}
function InstallPlugin_mzDanron()
{
  global $zbp;
  if (!$zbp->HasConfig('mzDanron')) {
    $zbp->Config('mzDanron')->version = 1;
    $zbp->Config('mzDanron')->keywords = "关键词";
    $zbp->Config('mzDanron')->description = "站点描述";
    $zbp->Config('mzDanron')->focusNums = 13;
    // $zbp->Config("mzDanron")->tootCount = 0;
    $zbp->SaveConfig('mzDanron');
  }
  $filesList = array("logo", "fav", "slide");
  foreach ($filesList as $key => $value) {
    $uFile = mzDanron_Path("u-{$value}");
    $vFile = mzDanron_Path("v-{$value}");
    if (!is_file($uFile)) {
      @mkdir(dirname($uFile));
      copy($vFile, $uFile);
    }
  }

  $uDir = mzDanron_Path("u-label");
  $vDir = mzDanron_Path("v-label");
  if (!is_dir($uDir) && is_dir($vDir)) {
    @mkdir($uDir);
    foreach (GetFilesInDir($vDir, "png") as $vFile) {
      $uFile = str_replace("var", "usr", $vFile);
      copy($vFile, $uFile);
    }
  }
  // 需要在模块重建前执行编译模板
  $zbp->BuildTemplate();
  // 重建模块内容
  $mod = $zbp->modulesbyfilename["tags"];
  $mod->Type = "div";
  $mod->Build();
  $mod->Save();
}
function UninstallPlugin_mzDanron()
{
  global $zbp;
  // 重建模块内容
  $mod = $zbp->modulesbyfilename["tags"];
  $mod->Type = "li";
  $mod->Build();
  $mod->Save();
}
